# coding: utf-8

import time, sys, os

sys.path.append(os.getcwd())
sys.path.append(os.getcwd() + '/../')

from HPSocket import TcpPack
import HPSocket.pyhpsocket as HPSocket
from Pack import Pack,Header


class Client(TcpPack.HP_TcpPackClient):
    EventDescription = TcpPack.HP_TcpPackServer.EventDescription

    def __init__(self, host='127.0.0.1', port=7889, head_flag=0x169, size=0x3FFFFF):
        super().__init__()

        self.host = host
        self.port = port
        self.head_flag = head_flag
        self.size = size

        self.close = True
        self.Pack = Pack()

    def IsClose(self):
        return self.close

    def start(self):
        return self.Start(host=self.host, port=self.port, head_flag=self.head_flag, size=self.size)

    @EventDescription
    def OnSend(self, Sender, ConnID, Data):
        print('[%d, 发送数据] < %s' % (ConnID, repr(Data)))
        return HPSocket.EnHandleResult.HR_OK

    def OnClose(self, Sender, ConnID, Operation, ErrorCode):
        self.close = True
        return HPSocket.EnHandleResult.HR_OK

    @EventDescription
    def OnConnect(self, Sender, ConnID):
        print('[%d, 连接服务] Success.' % ConnID)
        self.close = False
        return HPSocket.EnHandleResult.HR_OK

    def _OnReceive(self, Sender, ConnID, Data):
        print('[%d, 数据到达]' % (Sender), Data.decode(errors="replace"))
        return HPSocket.EnHandleResult.HR_OK

    @EventDescription
    def OnReceive(self, Sender, ConnID, Data):
        header, resdata = self.Pack.pack_unpack(Data)
        # print("数据到达",header.pack_index,header.pack_type,header.pack_count)
        if header.pack_type==2:
            self.Pack.add_response_data(header,resdata)
            return HPSocket.EnHandleResult.HR_OK

        if (header.pack_count == 1):
            return self._OnReceive(Sender, ConnID, resdata)
        else:
            if (header.pack_index < header.pack_count):
                self.Pack.add_receive_data(header, resdata)
            else:
                fulldata = self.Pack.get_receive_data(header)
                if (fulldata):
                    fulldata = fulldata + resdata
                    return self._OnReceive(Sender, ConnID, fulldata)
                else:
                    print("数据解析失败")

        return HPSocket.EnHandleResult.HR_OK

    def SendBytes(self, Buffer: bytes):
        '''
        发送字节集信息
        :param Buffer:
        :return: Bool
        '''
        header, msg_list = self.Pack.pack_uppack(max_pack=self.size, Buffer=Buffer)
        send = True
        for item in msg_list:
            if self.Send(self.Client, item) == False:
                send = False
                break
        return send

    def SyncSendBytes(self, Buffer: bytes):
        header, msg_list = self.Pack.pack_uppack(max_pack=self.size, Buffer=Buffer, pack_type=1)
        for item in msg_list:
            if self.Send(self.Client, item) == False:
                return None
        resdata = self.WaitResponse(header)
        return resdata

    def WaitResponse(self, header: Header, outTime = 3):
        print("header",header.pack_count,header.pack_type)
        t = time.time()
        resdata = None
        while time.time() - t < outTime:
            resdata = self.Pack.get_response_data(header=header)
            # time.sleep(0.1)
            if resdata:
                break
        return resdata

    def SendMsg(self, msg: str):
        '''
        发送文本信息
        :param msg:
        :return: Bool
        '''
        msg = msg.encode()
        return self.SendBytes(Buffer=msg)


if __name__ == '__main__':
    # pack_uphead(1,1,255,0)
    cnt = Client(host='127.0.0.1', port=7889, head_flag=0x169, size=0xFF)
    cnt.start()

    MSG = '''2023年5月24日至25日，中不边界问题专家组第十二次会议在不丹廷布举行。中方代表团由中国外交部边界与海洋事务司司长洪亮率领，
    不方代表团由不丹国际边界事务秘书长雷多·唐比率领。
    双方回顾了在中国昆明举行的专家组第十一次会议达成的积极共识，并就落实《关于加快中不边界谈判“三步走”路线图的谅解备忘录》进行了坦
    诚和建设性讨论。双方对专家组第十二次会议就落实“三步走”路线图取得的进展表示满意。
    '''

    while cnt.IsClose() == False:
        resdata = cnt.SyncSendBytes(MSG.encode())

        print("收到回复", resdata.decode())

        time.sleep(5)
    print("运行完毕")
